<?php
include_once 'ctype/base/baseField.php';

class Tags extends BaseField{
	var $template = "ctype/views/fields/tags.php";
	
	var $properties = array(
		"title"			=> "Texto",
		"description" 	=> "Descripción del campo texto"
		//values
	);
	
	function Tags(){
		parent::BaseField();
		
		$this->addStatic("javascript", "jquery.fcbkcomplete.js");
		
		$this->ci->load->model( "Tag_Model", "Tags");
		$this->ci->load->model( "Node_Model", "Nodes");
	}
	
	//@TODO funcion que obtendra los valores de las categorias a las que pertenece
	function view($node = NULL, $data = NULL){
		$value = $data;
		$name = $this->formName;
		$properties = $this->properties;
		
		$tags = $this->ci->Tags->get(array("status" => "all"));
		
		if($node != NULL){
			//$selected_categories = $this->ci->Nodes->getCategories($node->id);
			$selected_tags = $this->ci->Nodes->getTags($node->id);
		}
		
		ob_start();
		eval('?>'.preg_replace("/;*\s*\?>/", "; ?>", str_replace('<?=', '<?php echo ', file_get_contents($this->template, TRUE))));
		$view = ob_get_contents();
		@ob_end_clean();
		
		return $view;
	}
	
	function save($node = NULL, $data = NULL){
		//Eliminamos las categorias anteriores
		$this->ci->Nodes->deleteTags($node->id);
		/*
		if($data != NULL && $node != NULL){
			if(is_array($data)){
				foreach($data as $tag){
					//Eliminar la $category del nodo
					$this->ci->Nodes->deleteTag($node->id, $tag);
				}
			} else{
				//Eliminar la $category del nodo
				$this->ci->Nodes->deleteTag($node->id, $data);
			}
		}*/
		
		//Obtenemos las categorias seleccionadas
		$tags = $this->ci->input->post($this->formName);
		
		//Aquellas que sean strings las creamos.
		$process_tags = array();
		if($tags != NULL && $tags != ""){
			foreach($tags as $tag){
				if(!is_numeric($tag) && is_string($tag)){
					
					$tag_tmp = $this->ci->Tags->get(array(
						"url_name" => strtolower(url_title($tag)), 
						"status" => "all"
					));
					
					if($tag_tmp == FALSE || $tag_tmp == NULL){
						$data = array(
							"name" 		=> $tag, 
							"url_name"	=> strtolower(url_title($tag)),
							"visible"	=> 1
						);
						$id = $this->ci->Tags->create($data);
					} else{
						$id = $tag_tmp->id;
					}
					
					array_push($process_tags, $id);
				} else{
					array_push($process_tags, $tag);
				}
			}
			
			if($node != NULL){
				$this->ci->Nodes->addTags($node->id, $process_tags);
			}
		}
		
		return $process_tags;
	}
}
?>